"""
Case Type   : 小型化
Case Name   : 拉起双主
Create At   : 2024/8/7
Owner       : qumin
Description :
    1.获取安装包并解压
    2.更改属主和权限
    3.执行安装脚本安装主备节点
    4.查看数据库状态
    5.清理数据环境
Expect      :
    1.成功
    2.成功
    3.成功
    4.成功
    5.清理完成
History     :
"""

import os
import unittest
import time
from testcase.utils.Common import Common
from testcase.utils.Common import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class Lite(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_root = Node('PrimaryRoot')
        self.sta_root = Node('Standby1Root')
        self.pri_node = Node('PrimaryDbUser')
        self.sta_node = Node('Standby1DbUser')
        self.common = Common()
        self.constant = Constant()
        self.home_path = (os.path.dirname(macro.DB_PKG_PATH))
        self.pkg_path = os.path.join(self.home_path, 'pkg_path')
        self.install_path = os.path.join(self.home_path, 'install_path')
        self.data_path = os.path.join(self.home_path, 'data_path')
        self.u_name = 'u_install_0034'
        self.env_path = os.path.join('/home', self.u_name, '.bashrc')
        self.assert_msg = f'start datanode success'

    def test_upgrade(self):
        text = '----查询系统未使用端口----'
        self.log.info(text)
        port = []
        for i in range(3):
            port.append(self.common.get_not_used_port(self.pri_root))
            i = i + 1
        self.log.info(port)

        text = '----创建数据库用户和用户组;expect:创建成功----'
        self.log.info(text)
        self.common.create_user(self.pri_root, self.u_name)
        self.common.create_user(self.sta_root, self.u_name)

        text = '----创建数据，安装包等目录;expect:创建成功----'
        self.log.info(text)
        for d in (self.data_path, self.install_path, self.pkg_path):
            mkdir_cmd = f'if [ ! -d "{d}" ]; then mkdir -p "{d}"; \
                                echo "创建成功，目录已存在";' \
                        f'else echo "目录已存在无需创建"; rm -rf {d}/*; fi'
            result1 = self.common.get_sh_result(self.pri_root, mkdir_cmd)
            result2 = self.common.get_sh_result(self.sta_root, mkdir_cmd)
            self.assertIn('目录已存在', result1, '执行失败:' + text)
            self.assertIn('目录已存在', result2, '执行失败:' + text)

        text = '----step1:获取数据库安装包并解压;expect:成功----'
        self.log.info(text)
        cp_cmd = f'cd {macro.DB_PKG_PATH}; ' \
                 f'cp -r openGauss-Lite-*.tar.gz {self.pkg_path};'
        cp_res1 = self.common.get_sh_result(self.pri_root, cp_cmd)
        cp_res2 = self.common.get_sh_result(self.sta_root, cp_cmd)
        ls_cmd = f"ls {self.pkg_path}|grep -E '*Lite.*tar.gz'"
        file_name = self.common.get_sh_result(self.pri_root, ls_cmd)
        tar_cmd = f'cd {self.pkg_path};tar -xf {file_name}'
        self.log.info(tar_cmd)
        tar_res1 = self.common.get_sh_result(self.pri_root, tar_cmd)
        tar_res2 = self.common.get_sh_result(self.sta_root, tar_cmd)
        ls_res1 = self.common.get_sh_result(self.pri_root,
                                           f'ls -l {self.pkg_path}')
        self.assertIn('install.sh', ls_res1, '执行失败:' + text)
        ls_res2 = self.common.get_sh_result(self.sta_root,
                                           f'ls -l {self.pkg_path}')
        self.assertIn('install.sh', ls_res2, '执行失败:' + text)

        text = '----step2:更改属主和权限;expect:修改成功----'
        self.log.info(text)
        chm_cmd = f'chmod -R 755 {self.install_path} {self.data_path}  ' \
                  f'{self.pkg_path};chmod 777 {self.home_path}'
        self.log.info(chm_cmd)
        chm_result1 = self.common.get_sh_result(self.pri_root, chm_cmd)
        chm_result2 = self.common.get_sh_result(self.sta_root, chm_cmd)
        self.assertEqual('', chm_result1, '执行失败：' + text)
        self.assertEqual('', chm_result2, '执行失败：' + text)
        file_own = f'chown -R {self.u_name}:{self.u_name} ' \
                   f'{self.install_path} {self.data_path} ' \
                   f'{self.pkg_path};'
        self.log.info(file_own)
        file_msg1 = self.common.get_sh_result(self.pri_root, file_own)
        file_msg2 = self.common.get_sh_result(self.sta_root, file_own)
        self.log.info(file_msg1)
        self.log.info(file_msg2)
        self.assertEqual('', file_msg1, '执行失败：' + text)
        self.assertEqual('', file_msg2, '执行失败：' + text)

        text = '----step3:执行安装脚本安装主备节点;expect:安装成功----'
        self.log.info(text)
        text = '----step3.1:安装主节点;expect:安装成功----'
        self.log.info(text)
        su_cmd = f'su - {self.u_name}'
        install_cmd = f'cd {self.pkg_path}&&' \
              f'sh install.sh ' \
              f'-D {self.data_path} ' \
              f'-R {self.install_path} ' \
              f'-C port={port[0]} ' \
              f'-C \\\"replconninfo1=\'localhost={self.pri_node.db_host}' \
              f' localport={port[1]} ' \
              f'remotehost={self.sta_node.db_host} ' \
              f'remoteport={port[2]}\'\\\" ' \
              f'--mode primary --start' \
              f' && source {self.env_path}'
        execute_cmd1 = f'''expect <<EOF
                spawn {su_cmd}
                expect "$"
                send "{install_cmd}\\n"
                expect "input sql password:"
                send "{macro.COMMON_PASSWD}\\n"
                expect "input sql password:"
                send "{macro.COMMON_PASSWD}\\n"
                expect eof\n''' + '''EOF'''
        self.log.info(execute_cmd1)
        execute_msg1 = self.common.get_sh_result(self.pri_root, execute_cmd1)
        self.assertIn(self.assert_msg, execute_msg1, '执行失败' + text)
        text = '----step3.2:安装备节点;expect:安装成功----'
        self.log.info(text)
        su_cmd = f'su - {self.u_name}'
        install_cmd = f'cd {self.pkg_path}&&' \
              f'sh install.sh ' \
              f'-D {self.data_path} ' \
              f'-R {self.install_path} ' \
              f'-C port={port[0]} ' \
              f'-C \\\"replconninfo1=\'localhost={self.sta_node.db_host}' \
              f' localport={port[2]} ' \
              f'remotehost={self.pri_node.db_host} ' \
              f'remoteport={port[1]}\'\\\" ' \
              f'--mode primary --start' \
              f' && source {self.env_path}'
        execute_cmd2 = f'''expect <<EOF
                spawn {su_cmd}
                expect "$"
                send "{install_cmd}\\n"
                expect "input sql password:"
                send "{macro.COMMON_PASSWD}\\n"
                expect "input sql password:"
                send "{macro.COMMON_PASSWD}\\n"
                expect eof\n''' + '''EOF'''
        self.log.info(execute_cmd2)
        execute_msg2 = self.common.get_sh_result(self.sta_root, execute_cmd2)
        self.assertIn(self.assert_msg, execute_msg2, '执行失败' + text)
        text = '----step4:查看数据库状态;expect:成功----'
        self.log.info(text)
        ctl_cmd1 = f'su - {self.u_name} -c' \
                  f'"gs_ctl query -D {self.data_path} "'
        ctl_msg1 = self.common.get_sh_result(self.pri_root, ctl_cmd1)
        ctl_msg2 = self.common.get_sh_result(self.sta_root, ctl_cmd1)
        self.assertIn('local_role                     : Primary', ctl_msg1,
                      '执行失败' + text)
        self.assertIn('db_state                       : Normal', ctl_msg1,
                      '执行失败' + text)
        self.assertIn('local_role                     : Primary', ctl_msg2,
                      '执行失败' + text)
        self.assertIn('db_state                       : Normal', ctl_msg2,
                      '执行失败' + text)

    def tearDown(self):
        text = '----step5:清理环境;expect:成功----'
        self.log.info(text)
        uninstall_cmd = f'su - {self.u_name} -c "' \
                        f'source {self.env_path}&&' \
                        f'cd {self.pkg_path}&&' \
                        f'sh uninstall.sh --delete-data && ' \
                        f'sed -i \'/export/d\' {self.env_path} && ' \
                        f'source {self.env_path}";chmod 755 {self.home_path};'
        uninstall_msg1 = self.common.get_sh_result(self.pri_root, uninstall_cmd)
        uninstall_msg2 = self.common.get_sh_result(self.sta_root, uninstall_cmd)
        rm_cmd = f'rm -rf {self.install_path} {self.pkg_path};'
        self.log.info(rm_cmd)
        rm_result1 = self.common.get_sh_result(self.pri_root, rm_cmd)
        rm_result2 = self.common.get_sh_result(self.sta_root, rm_cmd)
        del_cmd = f'userdel -r {self.u_name}'
        del_result1 = self.common.get_sh_result(self.pri_root, del_cmd)
        del_result2 = self.common.get_sh_result(self.sta_root, del_cmd)
        self.assertIn('clean up related processes success',
                      uninstall_msg1, '执行失败' + text)
        self.assertIn('clean up related processes success',
                      uninstall_msg2, '执行失败' + text)
        self.assertEqual('', rm_result1, '执行失败:' + text)
        self.assertEqual('', rm_result2, '执行失败:' + text)
        self.assertEqual('', del_result1, '删除用户失败:' + text)
        self.assertEqual('', del_result2, '删除用户失败:' + text)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')